/**
 * Created by Administrator on 2018/5/10.
 */
define(function (require,exports,module) {
    require("./gante.css");
    require("../../../lib/echarts.min.js")
    require("../../../lib/fullcalendar/moment.min.js");
    var sTpl = require("./template.html");
    var VueComponent = Vue.extend({
        template: sTpl,
        data:function () {
            var form={
                startDate:'',
                endDate:'',
                flightNum:'',
                flightInfoId:''
            }
            return {
               form:form
            };

        },
        methods:{
            loadJs:function () {
                var $this = this;
                require.async("../../../lib/js-xlsx-master/shim.js",function (data) {
                    require.async("../../../lib/js-xlsx-master/xlsx.full.min.js", function (data) {
                        $this.jsLoaded=true;
                    });
                });
            },
            pickStartDate:function (val) {
                if(!val){
                    val=''
                }
               this.queryFlightPlane(val);
                this.form.startDate= val;
            },
            allFlight:function () {
                $("#container").hide();
                $("#father").show();
            },
            queryFlightPlane:function(val){
                var beforeHour=4;
                var afterHour=16;
                if(val){
                   var date= val;
                   var now =  new Date().getTime();
                   beforeHour =  (now -date)/1000/3600;
                   beforeHour =  parseInt(beforeHour);
                   afterHour  =  -(beforeHour - 24);
                }
                if(val){

                }
                axios.get(basepath +"/api/flightPlane/queryScheduleToday?beforeHour="+beforeHour+"&afterHour="+afterHour+"").then(function (response) {
                    father(response.data)
                })
            }

        },
        created:function (){

            axios.get(basepath +"/api/flightPlane/queryScheduleToday?beforeHour=4&afterHour=16").then(function (response) {
             //   abc(response.data[0]);
                father(response.data)
            })

        },
        activated:function () {
            messages.$emit('change','航班甘特图');
        }


    })
    //机务检测 特种服务 清洁安排 加油安排 加水安排 配餐安排 行李搬运
    module.exports = VueComponent;

    return VueComponent;
});

function father(schedules) {

    var dom = document.getElementById("father");
    // $("#app").attr("style","background:#333")
    var myChart = echarts.init(dom,'light');
    var app = {};
    option = null;
    var data = [];
    var dataCount = 1;
    var baseTime;

    var categories = [];
    schedules.forEach(function (da) {
        categories.push(da[0].flightInfo.flightNum+" "+da[0].originating+"-"+da[0].destination);
    })
    var types =
        {end:{name: 'end', color: 'white'},loading:{name: 'loading', color: '#909399'}};

    schedules.forEach(function (da,index) {
        var flightNumber=da[0].flightInfo.flightNum;
        var takeOffTime= new Date(da[0].takeOffTime).getTime();
        var arriveTime = new Date(da[0].arriveTime).getTime();

        var startTime ;
        var endTime ;
        da[1].schedulings.forEach(function (value) {
            var date = new Date(arriveTime).getTime();
            var start;
            if(value.groundServiceItemPo.timeStrategy=="落地时间"){
                date = new Date(arriveTime).getTime();
            }else{
                date = new  Date(takeOffTime).getTime();
            }
            if(value.groundServiceItemPo.beforeOrAfter=="基准实践前"){
                start=date-value.groundServiceItemPo.difference*60*1000
            }else{
                start=date+value.groundServiceItemPo.difference*60*1000
            }
            startTime=startTime?start<startTime?start:startTime:start;
            endTime = endTime?start>endTime?start:endTime:start;
          });

        baseTime=baseTime?baseTime:startTime;
        baseTime = baseTime>startTime?startTime:baseTime;
        endTime = endTime+1000*60*80;
        data.push({
            name: flightNumber,
            type:'loading',
            dat:da[0],
            schedules:da ,
            value: [
                index,
                startTime,
                endTime,
                endTime-startTime
            ],
            itemStyle: {
                normal: {
                    color:types['loading'].color,
                }
            }
        });
    })

    function renderItem(params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = 18;
         console.log(data[params.dataIndex].dat);

        return  {
            type: 'group',
            id: 'textGroup2',
            left: start[0],
            bottom:start[1] - height / 2,
            children:[
                {
                    type: 'rect',
                    shape: echarts.graphic.clipRectByRect({
                        x: start[0],
                        y: start[1] - height / 2,
                        width: end[0] - start[0],
                        height: height
                    }, {
                        x: params.coordSys.x,
                        y: params.coordSys.y,
                        width: params.coordSys.width,
                        height: params.coordSys.height
                    })
                ,style:{stroke:'#909399',fill:'#909399'}

                },
                {
                    type: 'circle',
                    shape: {
                        cx: start[0],
                        cy: start[1],
                        r: height/2
                    }
                    ,style:{stroke:'#909399',fill:'#909399'}
                },
                {
                    type: 'circle',
                    shape: {
                        cx: end[0],
                        cy: end[1],
                        r: height/2
                    }
                    ,style:{stroke:'#909399',fill:'#909399'}
                },

                {
                    type:'text',
                    style:{
                        text:moment(api.value(1)).format("HH:mm"),
                        fill:'#000',
                        x: start[0]-20,
                        y: start[1] - height
                    }
                },{
                    type:'text',
                    style:{
                        text:data[params.dataIndex].dat.flightInfo.flightNum,
                        fill:'#000',
                        x: start[0]+(end[0] - start[0])/2,
                        y: start[1] - height
                    }
                }
                ,{
                    type:'text',
                    style:{
                        text:moment(api.value(2)).format("HH:mm"),
                        fill:'#000',
                        x: end[0],
                        y: start[1] - height
                    }
                }
            ]
        }

    }


    var min = new Date(moment().format("YYYY-MM-DD HH")+":00:00").getTime()-2*3600*1000;
    var max = min+10*3600*1000;
    if(baseTime){
        baseTime = baseTime-30*1000*60;
    }
    option = {
        tooltip: {
            formatter: function (params) {

                return params.marker + params.data.dat.flightInfo.flightNum + ': ' + moment(params.value[1]).format("HH:mm:ss") +"-"+moment(params.value[2]).format("HH:mm:ss");
            }
        },
        title: {
            text: '航班运行状态',
            left: 'center'
        },

        grid: {
            left:'15%',
            height:400
        },
        xAxis: {
            min:min,
            max:max,
            scale: true,
            type:'time',
            interval:1000*600,
            axisLabel: {
                formatter: function (val) {
                    if(val%(3600*1000)==0){
                        return moment(val).format("HH:mm")
                    }

                }
            }
        },
        yAxis: {
            data: categories
        },
        series: [{
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
                normal: {
                    opacity: 0.8
                }
            },
            encode: {
                x: [1, 2],
                y: 0
            },
            data: data
        }]
    };
    // if(!baseTime){
    //     baseTime =new Date(moment().format("YYYY-MM-DD")+" 00:00:00").getTime() ;
    //     option.xAxis.min=baseTime;
    //     option.xAxis.max=baseTime+24*3600*1000-1000;
    // }
    if (option && typeof option === "object") {
        myChart.setOption(option, true);
        // setInterval(function(){
        //     data.forEach(function (da) {
        //         if(da.type!="end"){
        //             da.value[2]+=1000;
        //         }
        //
        //     })
        //     myChart.setOption(option, true);
        // },1000)
    }

    myChart.on('click', function (params) {
        $("#father").hide();
        $("#container").show();
        abc(params.data.schedules);
    })

}











function abc(schedule) {
    var dom = document.getElementById("container");
    // $("#app").attr("style","background:#333")
    var myChart = echarts.init(dom,'light');
    var app = {};
    option = null;
    var data = [];
    var dataCount = 1;
    var baseTime = new Date().getTime();
    var itemMap={'配餐服务':['配餐'],'清洁服务':['保洁'],
        '机务检测':['监护','勤务','上轮当','下客','关舱门','关闭货仓','撤轮档'],
        '特种服务':['摆渡车','除冰'],
        '加油服务':['加油'],
        '行李搬运':['卸货'],
        '加水服务':['加水'],
    }

    var categories = [];
    schedule[1].schedulings.forEach(function(da){
        if(itemMap[da.groundServiceItemPo.itemName]){
            categories=categories.concat(itemMap[da.groundServiceItemPo.itemName])
        }
       });
    categories.sort();
    var types =
        {end:{name: 'end', color: 'white'},loading:{name: 'loading', color: 'yellow'}};
    schedule[1].schedulings.forEach(function(da){
        if(itemMap[da.groundServiceItemPo.itemName]){
            itemMap[da.groundServiceItemPo.itemName].forEach(function (categorie) {
                var index=categories.indexOf(categorie);
                if(da.startDate){
                    var typeItem ='loading';
                    var startTime = new Date(da.startDate).getTime();
                    baseTime = startTime<baseTime?startTime:baseTime;
                    var endTime = new Date().getTime()-100;
                    if(da.endDate){
                        typeItem ='end';
                        endTime=new Date(da.endDate);
                    }
                    data.push({
                        name: categorie,
                        type:typeItem,
                        value: [
                            index,
                            startTime,
                            endTime,
                            endTime-startTime
                        ],
                        itemStyle: {
                            normal: {
                                color:types[typeItem].color,
                            }
                        }
                    });
                }
            })
        }
    })








    function renderItem(params, api) {
        var categoryIndex = api.value(0);
        var start = api.coord([api.value(1), categoryIndex]);
        var end = api.coord([api.value(2), categoryIndex]);
        var height = 2;

        return  {
            type: 'group',
            id: 'textGroup2',
            left: start[0],
            bottom:start[1] - height / 2,
            children: [
                {
                    type: 'line',
                    shape: {
                        x1: start[0],
                        y1: start[1],
                        x2: end[0],
                        y2: end[1]
                    }
                     ,style:{stroke:'#000 ',  lineWidth:height}
                },
                {
                    type: 'ring',
                    shape: {
                        cx: start[0],
                        cy: start[1],
                        r0: height*2,
                        r1: height
                    }
                    ,style:{stroke:'#000 ',fill:'rgb(245, 245, 245)',  lineWidth:height}
                },
                {
                    type: 'ring',
                    shape: {
                        cx: end[0],
                        cy: end[1],
                        r0: height*2,
                        r1: height
                    }
                    ,style:{stroke:'#000 ',fill:'rgb(245, 245, 245)',  lineWidth:height}
                }

            ]
        }
    }

    baseTime = baseTime-50*60*1000;

    option = {
        tooltip: {
            formatter: function (params) {
                return params.marker + params.name + ': ' + moment(params.value[1]).format("HH:mm") + '-'+moment(params.value[2]).format("HH:mm");
            }
        },
        title: {
            text: schedule[0].flightInfo.flightNum+'运行状态',
            left: 'center'
        },

        grid: {
            height:400
        },
        xAxis: {
            min: baseTime,
            scale: true,
            // max:new Date().getTime()+1000000*4,
            type:'time',
            axisLabel: {
                formatter: function (val) {
                    return moment(val).format("HH:mm")
                    //return Math.max(0, val - startTime) + ' ms';
                }
            }
        },
        yAxis: {
            data: categories
        },
        series: [{
            type: 'custom',
            renderItem: renderItem,
            itemStyle: {
                normal: {
                    opacity: 0.8
                }
            },
            encode: {
                x: [1, 2],
                y: 0
            },
            data: data
        }]
    };
    if (option && typeof option === "object") {
        myChart.setOption(option, true);
        setInterval(function(){
            data.forEach(function (da) {
                if(da.type!="end"){
                    da.value[2]+=1000;
                }

            })
            myChart.setOption(option, true);
        },1000)
    }



}





















